<template>
  <div>
    <div v-if="!onlyShowBtn" class="app-container">
      <div class="searBox">
        <el-form class="" :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="数据名称" prop="filename">
            <el-input
              v-filter-input
              style="width: 140px"
              v-model.trim="queryParams.filename"
              placeholder="请输入"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="导入状态" prop="state">
            <el-select
              class="el-input_search"
              v-model="queryParams.state"
              placeholder="请选择"
              clearable
              size="small"
              style="width: 140px !important"
            >
              <el-option label="未导入" value="0" />
              <el-option label="成功" value="1" />
              <el-option label="失败" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="数据时间" prop="organization">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="contBox">
        <div class="u-df-ed mb20" style="align-items: self-end">
          <el-button type="primary" plain :icon="showIcon ? 'el-icon-upload2' : ''" size="small" @click="handleImport">
            数据导入
          </el-button>
          <el-button
            v-if="showTemDownload"
            type="primary"
            plain
            icon="el-icon-download"
            size="small"
            @click="handleDownLoad"
          >
            模板下载
          </el-button>
        </div>

        <el-table v-loading="loading" :data="tableData" border :height="tableHeight ? tableHeight : contBoxHeight">
          <!--                <template slot='empty'>-->
          <!--                    <img src="../../assets/images/nodata.png" alt="" >-->
          <!--                    <p class="emptyText" style="line-height:0 !important;">{{ tableEmptyText }}</p>-->
          <!--                </template>-->
          <!--                <el-table-column type="selection" width="50" align="center" fixed/>-->
          <el-table-column type="index" width="55" label="序号" align="center" fixed />
          <el-table-column label="数据名称" align="center" prop="filename" width="140" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.filename || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="数据时间" align="center" prop="createTime" width="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.createTime || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="导入状态" align="center" prop="state" width="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{
                scope.row.state == null
                  ? '--'
                  : scope.row.state == '1'
                  ? '成功'
                  : scope.row.state == '2'
                  ? '失败'
                  : '未导入'
              }}
            </template>
          </el-table-column>
          <el-table-column label="失败原因" align="center" prop="reason" width="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.reason || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <div v-else class="u-df-st">
      <el-button
        type="primary"
        plain
        :icon="showIcon ? 'el-icon-upload2' : ''"
        size="small"
        @click="handleImport"
        :disabled="btnDisabled"
      >
        {{ impText ?? '数据导入' }}
      </el-button>
      <el-button
        v-if="showTemDownload"
        type="primary"
        plain
        icon="el-icon-download"
        size="small"
        @click="handleDownLoad"
        :disabled="btnDisabled"
      >
        模板下载
      </el-button>
    </div>
    <!-- 导入对话框 -->
    <el-dialog :visible.sync="upload.open" :before-close="handleCancel" width="664px" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">导入-</span>
        <span class="tit_con">{{ title }}</span>
      </div>
      <el-upload
        ref="upload"
        v-loading.fullscreen.lock="upload.loading"
        element-loading-text="上传中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :data="extraParams"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileErroe"
        :on-change="handleFileChange"
        :file-list="fileLists"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!--                <div class="el-upload__tip" slot="tip">-->
        <!--                    <div class="el-upload__tip" slot="tip">-->
        <!--                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
        <!--                    </div>-->
        <!--                    <span>仅允许导入xls、xlsx格式文件。</span>-->
        <!--                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>-->
        <!--                </div>-->
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" type="primary" plain size="small">取 消</el-button>
        <el-button type="primary" @click="submitFileForm" size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import { getDataImportList } from '@/api/index.js';
export default {
  name: 'dataImport',
  props: {
    showTemDownload: {
      type: Boolean,
      default: true,
    },
    showIcon: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: '',
    },
    templateTit: {
      type: String,
      default: '',
    },
    pageParams: {
      type: String,
      default: null,
    },
    uploadUrl: {
      type: String,
      default: null,
    },
    downloadUrl: {
      type: String,
      default: null,
    },
    onlyShowBtn: {
      type: Boolean,
      default: false,
    },
    tableHeight: {
      type: Number,
      default: NaN,
    },
    impText: {
      type: String | null,
      default: null,
    },
    extraParams: {
      type: Object,
      default: () => null,
    },
    btnDisabled: {
      type: Boolean,
      default: false,
    },
    tgxmParms: {
      type: Object,
      default: () => null,
    },
    showResolve: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      contBoxHeight: '80%',
      queryParams: {
        code: '',
        state: '',
        filename: '',
        startDate: '',
        endDate: '',
        pageNum: 1,
        pageSize: 10,
      },
      dateRange: [],
      tableData: [],
      total: 0,
      loading: false,
      upload: {
        loading: false,
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: '',
        // this.$store.state.global.fileUrl + "/businessbase/importBusinessUser/importBusinessUser"
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      fileLists: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (!this.onlyShowBtn) {
        this.contBoxHeight =
          document.getElementsByClassName('app-container')[0].clientHeight -
          this.$refs.queryForm.$el.clientHeight -
          135;
      }
    });
    this.upload.url = this.uploadUrl;
    if (!this.onlyShowBtn) this.getList();
  },
  methods: {
    getList() {
      this.queryParams.startDate = this.dateRange[0] || '';
      this.queryParams.endDate = this.dateRange[1] || '';
      this.queryParams.code = this.pageParams;
      this.loading = true;
      getDataImportList(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
        if (this.total > 0) {
          this.contBoxHeight =
            document.getElementsByClassName('app-container')[0].clientHeight -
            this.$refs.queryForm.$el.clientHeight -
            155 -
            30;
        } else {
          this.contBoxHeight =
            document.getElementsByClassName('app-container')[0].clientHeight -
            this.$refs.queryForm.$el.clientHeight -
            135;
        }
      });
    },
    handleImport() {
      if (this.tgxmParms) {
        if (this.tgxmParms.agreementContentType.length > 0 && this.tgxmParms.agreementEndTime.length) {
          this.upload.open = true;
        } else {
          this.$modal.msgError('请先选择服务年限和服务内容');
        }
      } else {
        this.upload.open = true;
      }
    },
    /** 下载模板操作 */
    handleDownLoad() {
      this.download('/businessbase/dataImportTemplate/download', { code: this.pageParams }, this.templateTit);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.loading = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.fileLists = [];
      if (response.code === 200) {
        this.$emit('handleFileSuccess', response?.data || response?.msg);
      }
      if (this.showResolve) {
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            '</div>',
          '导入结果',
          { dangerouslyUseHTMLString: true },
        );
      } else {
        if (response.code === 200) {
          this.$modal.msgSuccess(response?.msg);
        } else {
          this.$modal.msgError(response?.msg);
        }
      }
      //   // this.$modal.msgSuccess(response.msg);
      //   this.queryParams.state = '1';
      if (!this.onlyShowBtn) this.getList();
      // }else{
      //   // this.$modal.msgError(response.msg);
      //   this.queryParams.state = '2';
      //   this.getList();
      // }
    },
    handleFileErroe(err, file, fileList) {
      this.upload.loading = false;
      this.upload.isUploading = false;
      this.$modal.msgError('上传失败,请重新上传');
      this.fileLists = [];
      // this.queryParams.state = '2';
      // this.getList();
    },
    handleFileChange(file, fileList) {
      this.fileLists = fileList;
    },
    // 提交上传文件
    submitFileForm() {
      if (this.fileLists.length === 0) {
        this.$modal.msgError('请上传文件');
      } else {
        this.upload.loading = true;
        this.$refs.upload.submit();
      }
    },
    handleCancel() {
      this.upload.open = false;
      this.fileLists = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm('queryForm');
      this.handleQuery();
    },
  },
};
</script>

<style scoped lang="scss"></style>
